package cs575.server.services;

import java.nio.ByteBuffer;

import cs575.common.FantasyMessage;
import cs575.common.Player;
import cs575.server.FantasyServer;

/**
 * Service that updates a player's statistics in the master server player list.
 * No message is returned.
 */
public class UpdatePlayer {
	public void execute(FantasyMessage message) {
		ByteBuffer m = ByteBuffer.wrap(message.getMessage());

		int nSize = m.getInt();
		byte[] nBytes = new byte[nSize];
		m.get(nBytes);
		String name = new String(nBytes);

		if (FantasyServer.doesPlayerExist(name)) {
			Player p = FantasyServer.getPlayer(name);
			Player newPlayer = new Player(name, p.getPosition());

			// Get number of stat updates for this player.
			int numStats = m.getInt();

			for (int i = 0; i < numStats; i++) {
				// Get stat name.
				int statNameSize = m.getInt();
				byte[] statNameBytes = new byte[statNameSize];
				m.get(statNameBytes);
				String statName = new String(statNameBytes);
				// Get stat value.
				int statValue = m.getInt();
				// Update the player object.
				newPlayer.updateStat(statName, statValue);
			}

			// Update the player object in the server.
			FantasyServer.updatePlayerTable(newPlayer);
		}
	}
}
